package com.cdtu.handler;

import com.cdtu.utils.FileUtils;
import com.cdtu.utils.NetUtils;
import com.cdtu.vo.ChannelHandlerContextVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;


/**
 * @author Mika
 * @date 2025/03/01 12:05
 * 写指令
 **/
@Deprecated
@Slf4j
public class WriteOrderHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取当前连接信息
        ChannelHandlerContextVo current = NetUtils.bindParams(ctx);
//        log.info("WriteOrderHandler - {}", current.toString());
        // 读取配置文件
        JsonNode root = FileUtils.getJsonData("AILogiController.json");
        ArrayNode arrayNode = (ArrayNode)root.get("send2list");
//        for (JsonNode node : arrayNode) {
//            String IP = node.get("IP").asText();
//
//            if (!current.getReqIp().contains(IP)) continue;
//            // 连接 IP 在配置文件中，则下达 order
//            String[] orders = Order.generateOrder(true, node);
//            log.info("给 IP：{} 发送命令 {}", IP, Arrays.toString(orders));
//            byte[] bytes = Crc16Utils.getByteData(orders);
//            //
//            NetUtils.sendToClients(current.getClientIdToShort(), bytes);
//        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        StackTraceElement[] stackTrace = cause.getStackTrace();
//        log.error(cause.getLocalizedMessage());
//        for (StackTraceElement element : stackTrace) {
//            log.error("line: {}, {}, {} ", element.getLineNumber(), element.getMethodName(), element.getFileName());
//        }
//        cause.printStackTrace();
        ctx.close();
    }
}
